package com.quanyan.user.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.assets.entity.TbUserAssets;
import com.quanyan.assets.request.ReqCoupon;
import com.quanyan.assets.request.ReqUserInfo;
import com.quanyan.assets.response.RespOrderCoupon;
import com.quanyan.assets.service.CouponService;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.entity.RespMyLastActivity;
import com.quanyan.club.entity.vo.resp.MyNewestClubCard;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.platform.client.IPlaceDubboService;
import com.quanyan.platform.response.MyPlaceResponse;
import com.quanyan.statium.api.resp.RespUserLastGameEvent;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbUserFollowMapper;
import com.quanyan.user.mapper.UserInfoMapper;
import com.quanyan.user.model.db.TbChannelLayout;
import com.quanyan.user.model.db.TbLevel;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.db.TbUserFollowExample;
import com.quanyan.user.model.vo.request.ReqCommentQuery;
import com.quanyan.user.model.vo.request.ReqDynamic;
import com.quanyan.user.model.vo.request.ReqHomePage;
import com.quanyan.user.model.vo.response.*;
import com.quanyan.user.model.vo.response.my.*;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.service.*;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/2.
 */
@Service
public class HomePageServiceImpl implements HomePageService {
    private final static Logger logger = LoggerFactory.getLogger(HomePageServiceImpl.class);

    @Autowired
    private LayoutService layoutService;

    @Autowired
    private TopicService topicService;

    @Autowired
    private UserDynamicService userDynamicService;

    @Autowired
    private NewsImagesService newsImagesService;

    @Autowired
    private NewsUnReadService newsUnReadService;

    @Autowired
    private TaskEggService taskEggService;

    @Autowired
    private ClubOpenService clubOpenService;

    @Autowired
    private StadiumOpenService stadiumOpenService;

    @Autowired
    private IPlaceDubboService iPlaceDubboService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private TbUserFollowMapper userFollowMapper;

    @Autowired
    private UserQueryService  userQueryService;

    //用户默认头像地址
    @Value("${user_default_icon}")
    private String userDefaultIcon;

    @Autowired
    private LevelService levelService;

    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private UserAssetsService userAssetsService;

    @Autowired
    private PlaceClient placeClient;

    public RespHomePage queryHomePage(ReqHomePage reqHomePage){
        List<TbChannelLayout>  tbChannelLayouts =  layoutService.queryFindLayoutByModule(Constants.ChannelModule.find_channel);
        //todo 首页通栏加缓存
        RespHomePage respHomePage  = new RespHomePage();
        if (tbChannelLayouts != null && tbChannelLayouts.size() > 0){
            int temCount = 0;
            for ( TbChannelLayout tbChannelLayout : tbChannelLayouts ){

                if (tbChannelLayout.getNum() == 0)
                    continue;

                if (tbChannelLayout.getType().equals(Constants.ChannelCodeLayout.topic_type_code)){  //话题
                    TopicListInfoLayout topicListInfoLayout = new TopicListInfoLayout();
                    topicListInfoLayout.setSeq(tbChannelLayout.getSeq());
                    topicListInfoLayout.setTitle(tbChannelLayout.getTitle());

                    /** ========话题============= **/
                    ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
                    reqCommentQuery.setPageSize(tbChannelLayout.getNum());
                    List<RespTopicListInfo> lstTopic = topicService.findAllPage(reqCommentQuery).getObject();
                    topicListInfoLayout.setData(lstTopic);
                    respHomePage.setTopicListInfoLayout(topicListInfoLayout);
                    temCount += 1;

                }else if (tbChannelLayout.getType().equals(Constants.ChannelCodeLayout.dynamic_type_code)) {  //精选动态
                    DynamicDetailsLayout dynamicDetailsLayout = new DynamicDetailsLayout();
                    dynamicDetailsLayout.setSeq(tbChannelLayout.getSeq());
                    dynamicDetailsLayout.setTitle(tbChannelLayout.getTitle());

                    /** ========精选话题============= **/
                    ReqDynamic reqDynamic = new ReqDynamic();
                    reqDynamic.setType(UserConstants.DynamicType.choiceDy);
                    reqDynamic.setUid(reqHomePage.getUid());
                    reqDynamic.setPageSize(tbChannelLayout.getNum());
                    APIResponse<PageObj<List<RespDynamicDetail>>> response = userDynamicService.queryDynamic(reqDynamic);
                    if (response.isRet() && response.getData() != null){
                        dynamicDetailsLayout.setData(response.getData().getItems());
                    }else {
                        dynamicDetailsLayout.setData(new ArrayList<RespDynamicDetail>());
                    }

                    respHomePage.setSpecialDynamicsLayout(dynamicDetailsLayout);
                    temCount += 1;

                }else if (tbChannelLayout.getType().equals(Constants.ChannelCodeLayout.video_type_code)) {  //视频
                    VideoLayout videoLayout = new VideoLayout();
                    videoLayout.setSeq(tbChannelLayout.getSeq());
                    videoLayout.setTitle(tbChannelLayout.getTitle());

                    /** ========精选视频============= **/
                    ReqDynamic reqDynamic = new ReqDynamic();
                    reqDynamic.setType(UserConstants.DynamicType.specialVideo);
                    reqDynamic.setUid(reqHomePage.getUid());
                    reqDynamic.setPageSize(tbChannelLayout.getNum());
                    APIResponse<PageObj<List<RespDynamicDetail>>> response = userDynamicService.queryDynamic(reqDynamic);
                    if (response.isRet() && response.getData() != null){
                        videoLayout.setData(response.getData().getItems());
                    }else {
                        videoLayout.setData(new ArrayList<RespDynamicDetail>());
                    }
                    respHomePage.setVideoLayout(videoLayout);
                    temCount += 1;

                }
            }
            respHomePage.setCount(temCount);
        }
        return respHomePage;
    }


    @Override
    public APIResponse getMyIndex(Integer uid) {
        if (uid == null || uid <= 0) {
            return APIResponse.returnFail(ApiResponseEnum.COOKIES_IS_NULL);
        }

        MyIndex myIndex = new MyIndex();

        //设置用户基本信息
        TbUser tbUser = userQueryService.getUser(uid);
        RespUserInfoBase respUserInfoBase = new RespUserInfoBase();
        respUserInfoBase.setUid(tbUser.getId());
        respUserInfoBase.setGender(tbUser.getGender().intValue());
        respUserInfoBase.setNickName(tbUser.getNickName());
        respUserInfoBase.setIcon(tbUser.getIcon());
        respUserInfoBase.setRealName(tbUser.getName());
        respUserInfoBase.setMobile(tbUser.getMobile());

        RespCheckDarenAuth respCheckDarenAuth = httpClientService.checkDarenAuth(2,tbUser.getMobile());
        if (respCheckDarenAuth != null && respCheckDarenAuth.isRet() && respCheckDarenAuth.getData() != null
                && respCheckDarenAuth.getData().isHas_auth()) {
            respUserInfoBase.setIsDaren((short)1);
        }

        TbLevel tbLevel = levelService.getTbUserLevel(tbUser.getId()); // 等级信息
        if(tbLevel != null ) {
            respUserInfoBase.setLevel(tbLevel.getLevel());
        }
        myIndex.setUserInfoBase(respUserInfoBase);

        RespMyDynamicImages dynamicImages = newsImagesService.getMyDynamicImages(uid,3);
        RespUnReadCount respUnReadCount = newsUnReadService.queryUnReadNewsCount(uid);
        if (respUnReadCount != null) {
            dynamicImages.setUnreadCount(respUnReadCount.getAtCount() + respUnReadCount.getCommentCount() + respUnReadCount.getPraiseCount());  //设置未读消息
        }
        //设置我的动态信息
        myIndex.setMyDynamic(dynamicImages);

        SportAdvice sportAdvice = new SportAdvice();

        try {
            MyNewestClubCard myNewestClubCard = clubOpenService.getMyNewestClub(uid);

            if (myNewestClubCard != null ) {
                //设置俱乐部信息
                MyClubInfo myClubInfo = new MyClubInfo();
                myClubInfo.setCount(myNewestClubCard.getTotalCount());
                myClubInfo.setLogoUrl(myNewestClubCard.getClubLogo());
                myIndex.setMyClubInfo(myClubInfo);

                //设置俱乐部活动信息
                RespMyLastActivity myLastActivity = myNewestClubCard.getMyLastActivity();
                if (myLastActivity != null) {
                    if (myLastActivity.getActivityId() != null) {
                        ClubActivityInfo clubActivityInfo = new ClubActivityInfo();
                        clubActivityInfo.setCategory(myLastActivity.getCategoryName());
                        clubActivityInfo.setId(myLastActivity.getActivityId());
                        clubActivityInfo.setPlace(myLastActivity.getActivitySite());
                        clubActivityInfo.setStartTime(myLastActivity.getStartTime());
                        sportAdvice.setClubActivityInfo(clubActivityInfo);
                    }
                }
            }
        }catch (Exception e) {
            logger.error("获取俱乐部信息失败：{}", e);
        }

        //设置达人信息
        List<FollowDarenIcon> followDarenIcons =  userInfoMapper.getLastFollowDarenIcon(uid);
        if (followDarenIcons != null && followDarenIcons.size() > 0) {
            MyFocusDarenInfo myFocusDarenInfo = new MyFocusDarenInfo();
            if (followDarenIcons.get(0) != null ) {
                myFocusDarenInfo.setImageUrl(followDarenIcons.get(0).getIcon());
                TbUserFollowExample userFollowExample = new TbUserFollowExample();
                TbUserFollowExample.Criteria criteria = userFollowExample.createCriteria();
                criteria.andStateEqualTo((byte)0);
                criteria.andUidEqualTo(uid);
                criteria.andTypeEqualTo((byte)1);
                myFocusDarenInfo.setCount(userFollowMapper.countByExample(userFollowExample));
                myIndex.setMyFocusDarenInfo(myFocusDarenInfo);
            }
        }

        try {
            //设置赛事信息
            RespUserLastGameEvent respUserLastGameEvent = stadiumOpenService.getUserLastGameEvent(uid);
            if (respUserLastGameEvent != null) {
                myIndex.setJoinEventCount(respUserLastGameEvent.getAttendCount());
                if (respUserLastGameEvent.getGameEventId() > 0) {
                    EventsInfo eventsInfo = new EventsInfo();
                    eventsInfo.setId(respUserLastGameEvent.getGameEventId());
                    eventsInfo.setPlace(respUserLastGameEvent.getAddress());   //可能为空
                    eventsInfo.setCategoryId(respUserLastGameEvent.getCategoryId());   //
                    eventsInfo.setStartTime(respUserLastGameEvent.getGameStartTime());  //赛事时间
                    sportAdvice.setEventsInfo(eventsInfo);
                }

            }
        }catch (Exception e) {
            logger.error("获取赛事信息失败{}",e);
        }


        try {
            //设置场馆信息
            APIResponse<MyPlaceResponse> myPlaceResponse  = iPlaceDubboService.getStartingPlace(uid);

            if (myPlaceResponse != null && myPlaceResponse.getData() != null ) {
                MyPlaceResponse myPlace =  myPlaceResponse.getData();
                if (myPlace.getPlaceId() != null ){
                    BookPlaceInfo bookPlaceInfo = new BookPlaceInfo();
                    bookPlaceInfo.setId(myPlace.getPlaceId());
                    bookPlaceInfo.setCategory(myPlace.getCategoryName());

                    if (myPlace.getStartDate() != null && myPlace.getStartTime() != null) {
                        DateFormat df = new SimpleDateFormat("HH:mm:ss");
                        String strDateTime = DateUtils.convertFormatDateToString(DateUtils
                                .DATE_FORMAT_yyyy_MM_dd,new Date(myPlace.getStartDate()))
                                + " " + df.format(new Date(myPlace.getStartTime()));
                        bookPlaceInfo.setStartTime(DateUtils.strToDate(strDateTime,
                                DateUtils.DAY_DATE_FORMAT_HH_MM_SS).getTime());
                    }

                    bookPlaceInfo.setPlace(myPlace.getPlaceName());
                    sportAdvice.setBookPlaceInfo(bookPlaceInfo);
                }
                myIndex.setPalceCount(myPlace.getPlaceNum());

            }
        }catch (Exception e) {
            logger.error("获取场馆信息失败！{}", e);
        }

        myIndex.setSportAdvice(sportAdvice);   //设置运动提示

        myIndex.setServerTime(new Date().getTime());

        return APIResponse.returnSuccess(myIndex);
    }


    @Override
    public APIResponse getMyIndexInfo(Integer uid) {
        try {
            //获取用户资产基本信息
            UserAssetsBaseInfo userAssetsBaseInfo = getUserAssetsBaseInfo(uid);

            //获取用户基本信息
            UserBaseInfo userBaseInfo = getUserBaseInfo(uid);

            MyIndexInfo myIndexInfo = new MyIndexInfo();
            myIndexInfo.setUserAssetsBaseInfo(userAssetsBaseInfo);
            myIndexInfo.setUserBaseInfo(userBaseInfo);

            return APIResponse.returnSuccess(myIndexInfo);
        } catch (Exception e) {
            logger.error("获取首页信息失败:{}", e);
            return APIResponse.returnFail("获取首页失败",e.getMessage());
        }
    }

    /**
     * 获取用户基本信息
     *
     * @param uid
     * @return
     */
    private UserBaseInfo getUserBaseInfo(Integer uid) {
        TbUser user = userQueryService.getUser(uid);
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        if (user != null ) {
            userBaseInfo.setUid(uid);
            userBaseInfo.setGender(user.getGender());
            userBaseInfo.setIcon(user.getIcon());
            userBaseInfo.setMobile(user.getMobile());
            userBaseInfo.setNickName(user.getNickName());
            userBaseInfo.setLarkCode(user.getLarkCode());
        }

        return userBaseInfo;
    }

    /**
     * 获取用户资产基本信息
     *
     * @param uid
     * @return
     */
    private UserAssetsBaseInfo getUserAssetsBaseInfo(Integer uid) {
        APIRequest<ReqCoupon> apiRequest1 = new APIRequest<>();
        ReqCoupon reqCoupon = new ReqCoupon();
        reqCoupon.setUid(uid);
        reqCoupon.setStatus((byte) 1);
        reqCoupon.setPageNo(0);
        reqCoupon.setPageSize(5);
        apiRequest1.setData(reqCoupon);
        APIResponse<RespOrderCoupon> userCouponList = null;
        userCouponList = couponService.getReceiveCouponList(apiRequest1);

        APIRequest<ReqUserInfo> apiRequest2 = new APIRequest<>();
        ReqUserInfo userInfo = new ReqUserInfo();
        userInfo.setUid(uid);
        userInfo.setAssetsType((byte) 1);
        apiRequest2.setData(userInfo);
        APIResponse<List<TbUserAssets>> userAssets = userAssetsService.getUserAccumulateList(apiRequest2);

        //设置优惠券数量
        UserAssetsBaseInfo userAssetsBaseInfo = new UserAssetsBaseInfo();
        if (userCouponList != null && userCouponList.getData() != null) {
            userAssetsBaseInfo.setCouponNum(userCouponList.getData().getUseAmount());
        }

        //设置鸟蛋数量
        if (userAssets != null && userAssets.getData() != null && userAssets.getData().size() > 0) {
            TbUserAssets tbUserAssets = userAssets.getData().get(0);
            userAssetsBaseInfo.setEggsNum(tbUserAssets.getAccumulate().intValue());
        }

        // 设置会员卡数量
        Integer memberCardNum = placeClient.getMemberCardNum(uid);
        userAssetsBaseInfo.setMemberCardNum((memberCardNum == null) ? 0 : memberCardNum);
        return userAssetsBaseInfo;
    }
}
